#include <stdlib.h>
#include "dtk_types.h"

#define MIN(a,b) (((a) > (b)) ? (b) : (a))
#define MAX(a,b) (((a) > (b)) ? (a) : (b))

DBoolean dtk_region_init (DRegion* region)
{
    if (region == NULL)
    {
        return DTK_FALSE;
    }

    region->x1 = region->y1= region->x2 = region->y2 = 0;

    return DTK_TRUE;
}

DBoolean dtk_region_add(DRegion* dst, DRegion* src1, DRegion* src2)
{
    if (dst == NULL || src1 == NULL || src2 == NULL)
    {
        return DTK_FALSE;
    }

    dst->x1 = MIN(src1->x1, src2->x1);
    dst->y1 = MIN(src1->y1, src2->y1);
    dst->x2 = MAX(src1->x2, src2->x2);
    dst->y2 = MAX(src1->y2, src2->y2);

    return DTK_TRUE;
}

DBoolean dtk_region_translate(DRegion* dst, DInt x, DInt y)
{
    dst->x1 += x;
    dst->y1 += y;
    dst->x2 += x;
    dst->y2 += y;
    return DTK_TRUE;
}

DBoolean dtk_region_clip (DRegion* dst, DRegion* src)
{
    DRegion temp;

    temp.x1 = MAX(dst->x1, src->x1);
    temp.y1 = MAX(dst->y1, src->y1);
    temp.x2 = MIN(dst->x2, src->x2);
    temp.y2 = MIN(dst->y2, src->y2);

    if (temp.x1 > temp.x2 || temp.y1 > temp.y2)
    {
        return DTK_FALSE;
    }
    *dst = temp;    
    return DTK_TRUE;
}

DBoolean dtk_region_contains (DRegion* region, DInt x, DInt y)
{
    if ((x > region->x1) && (x < region->x2)
        && (y > region->y1) && (y < region->y2))
    {
        return DTK_TRUE;
    }

    return DTK_FALSE;
}

void dtk_region_from_rectangle (DRegion* region, DRectangle* rect)
{
    region->x1 = rect->x;
    region->y1 = rect->y;
    region->x2 = rect->x + rect->width;
    region->y2 = rect->y + rect->height;
}

DInt dtk_region_width(DRegion* region)
{
    if (region == NULL)
    {
        return 0;
    }

    return region->x2 - region->x1;
}

DInt dtk_region_height(DRegion* region)
{
    if (region == NULL)
    {
        return 0;
    }

    return region->y2 - region->y1;
}

DBoolean dtk_region_dump(DString string, DRegion* region)
{
    if (region == NULL)
    {
        return DTK_FALSE;
    }

    printf ("%s:region(%p) = (%d, %d, %d, %d)\n",
        string,
        region,
        region->x1,
        region->y1,
        region->x2,
        region->y2);

    return DTK_TRUE;
}


